package com.ruoyi.project.lely.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.R;

import com.ruoyi.common.exception.base.CommonException;
import com.ruoyi.common.SecurityUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.framework.aspectj.lang.annotation.DataSource;
import com.ruoyi.framework.aspectj.lang.enums.DataSourceType;
import com.ruoyi.project.lely.constant.CommonConstant;
import com.ruoyi.project.lely.bean.dto.LyAddressDTO;
import com.ruoyi.project.lely.bean.entity.LyAddress;
import com.ruoyi.project.lely.mapper.LyAddressMapper;
import com.ruoyi.project.lely.service.LyAddressService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Desc: 地址信息 实现类
 * @Author LuoYong
 * @Date 2022/1/17 18:14
 */
@DataSource(value = DataSourceType.SLAVE)
@Service
public class LyAddressServiceImpl extends ServiceImpl<LyAddressMapper, LyAddress> implements LyAddressService {

    /**
     * 添加修改
     *
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public R add(LyAddressDTO dto) {
        Long userId = SecurityUtils.getUserId();
        LyAddress address = new LyAddress();
        BeanUtils.copyProperties(dto, address);

        // 是否需要设为默认
        if (CommonConstant.DEFAULT_ADDRESS_YES.equals(dto.getIsDefault())) {
            //将本人所有默认的地址重置为非默认
            boolean update = this.update(
                    new LambdaUpdateWrapper<LyAddress>()
                            .eq(LyAddress::getUserId, userId)
                            .eq(LyAddress::getIsDefault, CommonConstant.DEFAULT_ADDRESS_YES)
                            .set(LyAddress::getIsDefault, CommonConstant.DEFAULT_ADDRESS_NO));
        }
        boolean b = this.saveOrUpdate(address);
        if (!b) {
            throw new CommonException("操作失败");
        }
        return R.ok("操作成功");
    }
}
